Automating Templ Generate in Neovim
Prelude
I've been using Neovim for the past four years as my Personalized Development Environment (PDE) of choise. Neovim gave me many rabbit holes to dive into including but not limited to:
- Understanding the inner workings of an IDE and the various parts to configure that makes it a PDE.
- Learning Lua, Neovim’s configuration and extension language, and using it to wire up tools like:
- nvim-treesitter for syntax highlighting.
- mason for downloading and managing Language Servers (LSPs).
- nvim-lspconfig for configuring and customizing LSPs.
- nvim-cmp , a completion engine that suggests code snippets.
- Debugging things by digging into system files (because nothing ever works on the first try). This led me down a deeper rabbit hole of UNIX system and Linux research.
- Becoming more comfortable with the terminal and command-line interfaces (CLIs).
Why Automate templ generate
?
The structure of this website follows:
Templ provides a command-line interface that requires running templ generate
to convert .templ
files into Go code. However, manually running this command after every file change is tedious and disrupts workflow. As programmers, we naturally look for ways to automate repetitive tasks.
If you use Neovim (there might be a way to replicate this for your editor of choise), autocmds provide an excellent way to automate this process.
Setting Up the Autocmd
We can automatically run templ generate after saving a .templ
file by adding the following autocmd to the Neovim configuration (e.g., init.lua or another Lua file):
vim.api.nvim_create_autocmd({ 'BufWritePost' }, {
desc = 'Run templ generate on save',
group = [your-augroup], -- Replace with your autocmd group or remove if unnecessary
pattern = { '*.templ' },
callback = function()
vim.cmd(':silent !templ generate')
end
})
Let's break this down. We're using nvim_create_autocmd
to create a new autocmd. As args it takes the following:
events
: The first argument is a table (Lua’s all-purpose data structure) that defines the events that trigger the callback. You can specify multiple events if needed. You can find all the events here.opts
: The second argument includes various options, like the file pattern to match and the callback itself. The callback can be either a Lua function or a Vimscript function name as a string, more information here.
Replace [your-augroup]
with an autocmd group to keep things organized. This is useful for removing or executing a group of autocmds. If you need to create one, use:
local templ_group = vim.api.nvim_create_augroup('[YourGroupName]', { clear = true })
If you work with Templ frequently, this small automation can save time and streamline your workflow. Just set it up once, and let Neovim take care of the rest. Happy coding!